package com.liao.auth.controller;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.liao.auth.fegin.MemberFeignService;
import com.liao.common.constant.SessionEnum;
import com.liao.common.dto.WechatLoginRequest;
import com.liao.common.entity.member.UserEntity;
import com.liao.common.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author: ljt
 * @Description: 登录认证接口
 * @DateTime: 2025/3/14 下午4:55
 **/
@RestController
@RequestMapping("/auth/login")
public class LoginController {

    @Autowired
    private MemberFeignService memberFeignService;

//    @RequestMapping("/setKey")
//    public Object setKey(HttpServletRequest request) {
//        StpUtil.getSession().set("name", "123");
//        return StpUtil.getSession().get("name");
//    }
//
//    @RequestMapping("/getKey")
//    public Object getKey(HttpServletRequest request) {
//        boolean login = StpUtil.isLogin();
//        Object loginId = StpUtil.getLoginId();
//
//        System.out.println(StpUtil.isLogin());
//        return StpUtil.getSession().get("name");
//    }

    /**
     * 测试模拟登录获取token接口（测试）
     *
     * @param request
     */
    @RequestMapping("/login")
    public void login(HttpServletRequest request) {

        StpUtil.login("111");
        UserEntity user = new UserEntity();
        user.setUserId(1111);
        StpUtil.getSession().set(SessionEnum.USER_INFO_KEY, user);
    }

    /**
     * 微信登录
     */
    @PostMapping(value = "/Wxlogin")
    public UserEntity Wxlogin(@RequestBody WechatLoginRequest request) {

        Result<UserEntity> r = memberFeignService.WxLogin(request);


        if (r.getCode() == 200) {
            UserEntity user = r.getData();

            StpUtil.login(user.getUserId());
            StpUtil.getSession().set(SessionEnum.USER_INFO_KEY, user);
            SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
            user.setToken(tokenInfo.getTokenValue());

            return user;
        }

//        return R.error("登录失败");
        throw new RuntimeException("登录失败");
    }


}
